<template>
  <div id="LabInstrSetup">
    <Breadcrumb content="基础规则" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="50">
          <div class="tableBox">
            <vxe-toolbar perfect>
              <template #buttons>
                <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新"  @click="findWindowList"></vxe-button>
                <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteWindow"></vxe-button>
              </template>
            </vxe-toolbar>
            <vxe-table ref="callWindowTable" :border="'inner'" align="left" class="mytable-scrollbar" height="auto" :loading="loading" :data="windowList" :expand-config="{ expandAll: true, reserve: true }" :row-config="{ isCurrent: true, isHover: true }" :keyboard-config="{
                    isArrow: true,
                    isTab: true,
                    isEdit: true
                  }" :edit-config="{ trigger: 'dblclick', mode: 'row', showStatus: true }" resizable show-overflow keep-source @current-change="roleRowClick">
              <vxe-column type="checkbox" width="30px"></vxe-column>
             <vxe-column field="winCode" title="窗口code">
               <template #default="{ row }">
                  <span @click="navigateToDetail(row.winCode)" style="color: blue; cursor: pointer;">
                   {{ row.winCode }}
                 </span>
               </template>
             </vxe-column>
              <vxe-column field="winName" title="窗口名称"> </vxe-column>
              <vxe-column field="sampleTypeCode" title="采样类型">
                <template #default="{ row }">
                 {{getSampleTypeName(row.sampleTypeCode)}}
                </template>
              </vxe-column>
              <vxe-column field="seq" title="顺序"> </vxe-column>
              <vxe-column field="isEnable" title="是否启用" width="80" >
                <template #default="{ row }">
                  <span :style="{ color: row.isEnable === 1 ? 'green' : (row.isEnable === 2 ? 'orange' : 'red') }">
                     {{ row.isEnable === 1 ? '启用' : (row.isEnable === 2 ? '暂停' : '关闭') }}
                  </span>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <!-- 检验仪器基本信息表单 -->
          <CallRuleForm ref="refFormData" @getTableData="findWindowList" />
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import Breadcrumb from '@/components/Breadcrumb.vue';
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import { pageSizes, formatDateTime } from '../../../utils/common';
import { Splitpanes, Pane } from 'splitpanes';
import { AppStore } from '../../../stores/store';
import { VxeNotifyType, VxeMessage } from '../../../utils/CommonMessage';
import CallRuleForm from './components/CallRuleForm.vue';
import {isEmpty} from "lodash"; //检验仪器基本信息表单
// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
let store = AppStore();
let workGroupList: any = reactive([]); //检验组option
let instrClassList: any = reactive([]);

let form = reactive({
  funcName: '', //仪器名称
  orgId: store.userInfo.orgId,
  orgName: store.userInfo.orgName
});

let callWindowTable = ref(); //检验仪器表格标记ref
let windowList: any = reactive([]); //检验仪器表格数据
let callTypeList:any = reactive([])
let loading = ref(false); //查询按钮加载
let saveLoading = ref(false);

let refFormData: any = ref(null); //检验仪器基本信息表单ref

// 方法定义区 =============

// 页面加载时
onMounted(() => {
  getSampleTypeList();
  findWindowList(); //获取检验仪器表格数据
});


function navigateToDetail(winCode: string) {
  const targetUrl = `/zjScreen?code=${winCode}`;
  window.open(targetUrl, '_blank'); // 在新标签页中打开
}
function getSampleTypeList() {

  callTypeList.length = 0; //放入数据前清空数据
  const url = '/callNum/sampleType/findSampleTypeList';
  proxy.$http
      //注意此处的数据条数
      .get(url, {
        params: {
          seachValue: ''
        }
      })
      .then((res: any) => {
        callTypeList.push(...res.data);
      })
      .catch((err: any) => {
        VxeMessage('获取获取采样类型列表失败',VxeNotifyType.error)
      });
}

function getSampleTypeName(sampleTypeCode){
  if (callTypeList.length>0){
    for (let i = 0; i < callTypeList.length; i++) {
      if (callTypeList[i].sampleTypeCode === sampleTypeCode) {
        return callTypeList[i].sampleTypeName;
      }
    }
  }
}

// 获取检验仪器表格数据
function findWindowList() {
  loading.value = true;
  windowList.length = 0;
  const url = '/callNum/window/findWindowList';
  proxy.$http
    .get(url)
    .then((res: any) => {
      windowList.push(...res.data);
      roleRowClick({
        row: windowList[0],
        rowIndex: 0
      });
      loading.value = false;
    })
    .catch((err: any) => {
      loading.value = false;
      VxeMessage('搜索功能列表异常', VxeNotifyType.error);
    });
}

function deleteWindow() {
  const sltCampusAreas = (proxy.$refs.callWindowTable as any).getCheckboxRecords();
  if (!(sltCampusAreas.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
        .$confirm('确定要删除当前勾选的数据？', '提示', {
          cancelButtonClass: 'cancel-button',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(async () => {
          //后台删除数据
          const delCampusAreaList = sltCampusAreas.filter((p: any) => !isEmpty(p.id));
          if (delCampusAreaList.length > 0) {
            const url = '/callNum/window/batchDeleteWindow';
            proxy.$http
                .post(url, delCampusAreaList)
                .then((res: any) => {
                  findWindowList(); // 获取检验仪器表格数据
                  VxeMessage(res.status.msg, VxeNotifyType.success);
                })
                .catch((err: any) => {
                  VxeMessage(err, VxeNotifyType.error);
                });
          }
        })
        .catch((err: any) => {
          // VxeMessage(err, VxeNotifyType.error);
        });
  }
}
// 点击表格当前行
function roleRowClick({ row, rowIndex }: any) {
  refFormData.value.initPage(row); //传递给右侧基本信息表单
  (proxy.$refs.callWindowTable as any).setCurrentRow(row);
}

//下拉选择之后触发保存当前
function selectchange(e: any) {
  e.aimKeys.forEach((item: any) => {
    if (e.isChild) {
      windowList[e.childIndex][item.targetField] = e.row[item.sourceField];
      if (item.targetField === 'reportUnitEntity') {
        windowList[e.childIndex].groupNo = e.row[item.sourceField].id;
      }
    } else {
      //表单用
    }
  });
}

// 点击修改新增保存
async function saveList() {
  saveLoading.value = true;
  // 获取表格实例
  const $Xtable = callWindowTable.value;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords();

    // 拿到列表中id为空的为新增
    const InsertRecords = await $Xtable.getInsertRecords().filter((m: any) => {
      return m.id === '';
    });

    // 遍历发起请求  将筛选出有id的每一个对象（修改过的） 作为参数传递给后端
    updateRecords.forEach((e: any) => {
      let data = e;

      proxy.$http
        .post('/lis/instrSetup/edit', data)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('修改异常', VxeNotifyType.error);
        });
    });

    //新增
    InsertRecords.forEach((e: any) => {
      proxy.$http
        .post('/lis/instrSetup/addInstrSetup', e)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('创建成功', VxeNotifyType.success);
          } else {
            return;
          }
        })
        .catch((err: any) => {
          VxeMessage('创建异常', VxeNotifyType.error);
        });
    });
    setTimeout(() => {
      findWindowList();
      saveLoading.value = false;
    }, 500);
  } else {
    return;
  }
}

//这个月第一天日期
function getThisMonthFirstDay() {
  let today = new Date();
  today.setDate(1);
  today.setHours(0, 0, 0, 0);
  return today;
}
//当前日期
function getThisMonthNewDay() {
  let today = new Date();
  return today;
}

function formatOperateTime({ cellValue, row, column }) {
  // 假设cellValue是一个时间戳，你可以使用Date对象将其格式化为包含毫秒的形式
  const date = new Date(cellValue);
  return formatDateTime(date, 'yyyy-MM-dd hh:mm:ss.SSS'); // 这会返回包含毫秒的 ISO 8601 格式的时间字符串
}
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
</script>

<style lang="scss" scoped>
#LabInstrSetup {
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    .el-tabs {
      height: 100%;
      :deep(.el-tabs__content) {
        height: calc(100% - 39px);
        padding: 0px;
        #pane-0,
        #pane-1 {
          height: 100%;
        }
      }
    }
    .area {
      background-color: $base-white;
    }

    // 附加按钮间距
    .button-blue,
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 查询按钮
    .SearchBtn {
      margin-right: 5px;
    }

    .tableBox {
      height: calc(100% - 40px);

      .vxe-table {
        height: calc(100%);

        :deep(.vxe-table--render-wrapper) {
          height: 100%;

          .vxe-table--main-wrapper {
            height: 100%;

            .vxe-table--body-wrapper {
              height: calc(100% - 26px) !important;
            }
          }
        }
      }
    }
  }
}
</style>
